<?php

/**
 * 高德地图
 */
class Amap {

    private $apikey;

    public function __construct() {
        $this->apikey='c11f35d41f51a54a55416afe0b75c67b';//应用apikey
    }

    /**
     * 高德地图获取交通费
     * @param $lng1
     * @param $lat1
     * @param $lng2
     * @param $lat2
     * @return bool|string
     */
    public function getFareData($lng1,$lat1,$lng2,$lat2){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://restapi.amap.com/v5/direction/driving?key=".$this->apikey."&origin=".$lng1.",".$lat1."&destination=".$lng2.",".$lat2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        if(!$response || $response=='') return ['code'=>0,'msg'=>'地图api调用失败'];
        $result = json_decode($response,true);
        if(!$result)  return ['code'=>0,'msg'=>'路线规划失败'];
        if($result['status']=='1' && $result['infocode']=='10000'){
            $distance = isset($result['route']['paths'][0]['distance'])?bcdiv($result['route']['paths'][0]['distance'],1000,2):0;
            return ['code'=>1,'msg'=>'ok','data'=>['distance'=>$distance,'taxi_cost'=>$result['route']['taxi_cost']]];
        }else{
            return ['code'=>0,'msg'=>'路线规划错误：'.$result['info']];
        }
    }

    /**
     * 根据ip获取城市信息
     * @param $ip
     * @return array
     */
    public function getCityByIp($ip){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://restapi.amap.com/v3/ip?ip=".$ip."&output=json&key=".$this->apikey,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        if(!$response || $response=='') return ['code'=>0,'msg'=>'地图api调用失败'];
        $result = json_decode($response,true);
        if(!$result)  return ['code'=>0,'msg'=>'获取失败'];
        if($result['status']=='1' && $result['infocode']=='10000'){
            return ['code'=>1,'msg'=>'ok','data'=>['city'=>$result['city'],'adcode'=>$result['adcode']]];
        }else{
            return ['code'=>0,'msg'=>'获取错误：'.$result['info']];
        }
    }

}